package com.wandousoushu.jiusen.ui.my

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.wandousoushu.jiusen.MyApplication
import com.wandousoushu.jiusen.MyApplication.Companion.instance
import com.wandousoushu.jiusen.R
import com.wandousoushu.jiusen.help.BookHelp
import com.wandousoushu.jiusen.ui.login.LoginActivity
import com.wandousoushu.jiusen.ui.widget.image.CircleImageView
import com.wandousoushu.jiusen.ui.widget.image.MyUserPhoto
import com.wandousoushu.jiusen.ui.widget.image.VipImageView
import com.wandousoushu.jiusen.util.*
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL

class MyFragment : Fragment() {
    private var menu1LinearLayout: LinearLayout? = null
    private var menu2LinearLayout: LinearLayout? = null
    private var menu3LinearLayout: LinearLayout? = null
    private var menu4LinearLayout: LinearLayout? = null
    private var menu5LinearLayout: LinearLayout? = null
    private var menu6LinearLayout: LinearLayout? = null
    private var userInfoLinearLayout: LinearLayout? = null
    private var nickNameTextView: TextView? = null
    private var phoneNumTextView: TextView? = null
    private var vipImageView: ImageView? = null
    private var tx: MyUserPhoto? = null
    private var exitTextView: TextView? = null
    private var reNewTextView: TextView? = null
    private var endTimeTextView: TextView? = null

    override fun onCreateView(inflater: LayoutInflater,
                              container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val root = inflater.inflate(R.layout.fragment_my, container, false)
        menu1LinearLayout = root.findViewById(R.id.my_menu1)
        menu1LinearLayout!!.setOnClickListener(View.OnClickListener {
            if (MyApplication.instance.isLogin) {
                startActivity<BookMarkActivity>()
            } else {
                startActivity<LoginActivity>()
            }
        })
        menu2LinearLayout = root.findViewById(R.id.my_menu2)
        menu2LinearLayout!!.setOnClickListener(View.OnClickListener {
            if (MyApplication.instance.isLogin) {
                startActivity<FeedbackActivity>()
            } else {
                startActivity<LoginActivity>()
            }
        })
        menu3LinearLayout = root.findViewById(R.id.my_menu3)
        menu3LinearLayout!!.setOnClickListener(View.OnClickListener {
            startActivity<ExemptionActivity>()
        })
        menu4LinearLayout = root.findViewById(R.id.my_menu4)
        menu4LinearLayout!!.setOnClickListener(View.OnClickListener {
            if (!instance.isWxUser) {
                if (MyApplication.instance.isLogin) {
                    startActivity<AccountManagerActivity>()
                } else {
                    startActivity<LoginActivity>()
                }
            }
        })
        menu5LinearLayout = root.findViewById(R.id.my_menu5)
        menu5LinearLayout!!.setOnClickListener(View.OnClickListener {
            BookHelp.clearCache()
            FileUtils.deleteFile(requireActivity().cacheDir.absolutePath)
            toast(R.string.clear_cache_success)
        })
        menu6LinearLayout = root.findViewById(R.id.my_menu6)
        menu6LinearLayout!!.setOnClickListener(View.OnClickListener {
            startActivity<AboutActivity>()
        })
        userInfoLinearLayout = root.findViewById(R.id.my_ll_userinfo)
        userInfoLinearLayout!!.setOnClickListener(View.OnClickListener {
            if (!MyApplication.instance.isLogin) {
                startActivity<LoginActivity>()
            }
        })
        nickNameTextView = root.findViewById(R.id.my_tv_nickname)
        phoneNumTextView = root.findViewById(R.id.my_tv_phone)
        reNewTextView = root.findViewById(R.id.my_tv_renew)
        reNewTextView!!.setOnClickListener(View.OnClickListener {
            if (MyApplication.instance.isLogin) {
                startActivity<VipActivity>(
                        Pair("isrenew", true)
                )
            }
        })
        endTimeTextView = root.findViewById(R.id.my_tv_vip_endtime)
        vipImageView = root.findViewById(R.id.my_iv_vip)
        vipImageView!!.setOnClickListener(View.OnClickListener {
            if (MyApplication.instance.isLogin) {
                startActivity<VipActivity>(
                        Pair("isrenew", false)
                )
            } else {
                startActivity<LoginActivity>()
            }
        })
        tx = root.findViewById(R.id.my_iv_tx)
        exitTextView = root.findViewById(R.id.my_btn_exit)
        return root
    }

    private fun InitData() {
        if (MyApplication.instance.isLogin) {
            nickNameTextView!!.text = instance.nickName
            phoneNumTextView!!.text = instance.phoneNum
            if (instance.isWxUser) {
                setImageURL(instance.userinfo.avatar)
                menu4LinearLayout!!.gone()
                exitTextView!!.visible()
                exitTextView!!.setOnClickListener(View.OnClickListener {
                    context?.putPrefString("account", "")
                    context?.putPrefString("password", "")
                    context?.putPrefString("wxopenid", "")
                    val intent = Intent(context, LoginActivity::class.java)
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
                    startActivity(intent)
                })
            } else {
                menu4LinearLayout!!.visible()
                exitTextView!!.gone()
                tx!!.setImageResource(R.drawable.def_tx)
            }
            if (instance.isVip) {
                vipImageView!!.gone()
                tx!!.setIsVip(1)
                reNewTextView!!.visible()
                endTimeTextView!!.visible()
                endTimeTextView!!.text = instance.userinfo.is_vip_endtime + "到期"
            } else {
                vipImageView!!.visible()
                tx!!.setIsVip(0)
                reNewTextView!!.gone()
                endTimeTextView!!.gone()
            }
        } else {
            nickNameTextView!!.text = ""
            phoneNumTextView!!.text = ""
            reNewTextView!!.gone()
            endTimeTextView!!.gone()
            exitTextView!!.gone()
            vipImageView!!.gone()
        }

    }

    override fun onResume() {
        super.onResume()
        InitData()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden) {
            toast("yincang")
        } else {
            InitData()
        }
    }

    private val mHandle: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                2 -> Toast.makeText(requireContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show()
                4 -> tx!!.setImageBitmap(msg.obj as Bitmap)
            }
        }
    }

    //设置网络图片
    fun setImageURL(path: String?) {
        //开启一个线程用于联网
        object : Thread() {
            override fun run() {
                try {
                    //把传过来的路径转成URL
                    val url = URL(path)
                    //获取连接
                    val connection = url.openConnection() as HttpURLConnection
                    //使用GET方法访问网络
                    connection.requestMethod = "GET"
                    //超时时间为10秒
                    connection.connectTimeout = 10000
                    //获取返回码
                    val code = connection.responseCode
                    if (code == 200) {
                        val inputStream = connection.inputStream
                        //使用工厂把网络的输入流生产Bitmap
                        val bitmap = BitmapFactory.decodeStream(inputStream)
                        //利用Message把图片发给Handler
                        val msg = Message.obtain()
                        msg.obj = bitmap
                        msg.what = 4
                        mHandle.sendMessage(msg)
                        inputStream.close()
                    }
                } catch (e: IOException) {
                    e.printStackTrace()
                    //网络连接错误
                }
            }
        }.start()
    }
}